#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

void delay_handler(int sig)
{
    int i = 0;
    printf("begin delay handler...\n");
    for(i = 0; i < 5; i++) {
        printf("sig(%d) - sleep %d ...\n", sig, i);
        sleep(1);
    }
    printf("end delay handler...\n");
}

int r_read(char* data, int len)
{
    int ret = -1;
    while(data && (ret = read(STDIN_FILENO, data, len-1)) == -1 && errno == EINTR) {
        printf("restart syscall mannually...\n");
    }
    
    if( ret != -1 ) {
        data[ret] = 0;
    }
    return ret;
}

int main(void)
{
    char buf[32] = {0};
    struct sigaction act = {0};
    
    act.sa_handler = delay_handler;
    act.sa_flags = SA_RESTART | SA_NODEFER;
    
    sigaddset(&act.sa_mask, 40);
    sigaddset(&act.sa_mask, SIGINT);
    
    sigaction(40, &act, NULL);
    sigaction(SIGINT, &act, NULL);
    
    r_read(buf, 32);
    printf("input: %s\n", buf);
    return 0;
}

